import { NavBar, DatePicker } from 'antd-mobile'
import './index.scss'
import { useState, useMemo } from 'react'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'
import { groupBy } from 'lodash'
import DailyBill from '@/components/DailyBill'

const Month = () => {

  const [dateVisible, setDateVisible] = useState(false)

  // useState 也可以用函数的返回值来作为默认值（如果需要一段逻辑处理后才能得到默认值）
  const [curMonth, setCurMonth] = useState(() => dayjs().format('YYYY | M'))

  const dateConfirm = (date) => {
    setCurMonth(dayjs(date).format('YYYY | M'))
    setDateVisible(false)
  }

  const { billList } = useSelector(state => state.bill)

  console.log('[ billList ] >', billList)

  const monthGroup = useMemo(() => {
    // 计算处理，将计算结果返回
    return groupBy(billList, (item) => dayjs(item.date).format('YYYY | M'))
  }, [billList])

  console.log('[ monthGroup ] >', monthGroup)

  const overview = useMemo(() => {

    const curMonthBillList = monthGroup[curMonth]

    if (!curMonthBillList) return { pay: 0, income: 0, total: 0 }

    // 是负数
    const pay = curMonthBillList.filter(v => v.type === 'pay').reduce((sum, v) => sum + v.money, 0)

    const income = curMonthBillList.filter(v => v.type === 'income').reduce((sum, v) => sum + v.money, 0)

    const total = pay + income

    return { pay, income, total }
  }, [monthGroup, curMonth])

  console.log('[ overview ] >', overview)

  // function fn() {
  //   // 这里有一万行代码，耗时一分钟，算出一个数据（当月份变化的时候）
  //   console.log('执行了一万行代码');
  // }
  // fn()
  // 用useMemo可以解决这个问题

  // 每天的统计数据列表 [
  const dailyBillList = useMemo(() => {
    // 提取当月的收支列表
    const curMonthBillList = monthGroup[curMonth]
    if (!curMonthBillList) return []

    // 将当月的收支列表 按 每天进行分组
    const dailyBillObj = groupBy(curMonthBillList, (v) => dayjs(v.date).format('YYYY-MM-DD'))

    // 循环每天的列表 映射成统计数据对象 { date, pay, income, total }
    return Object.entries(dailyBillObj).map(([k, v]) => {
      // k => 2022-10-22
      // v => [ { type, money, ... } ]
      const pay = v.filter(v => v.type === 'pay').reduce((sum, v) => sum + v.money, 0)
      const income = v.filter(v => v.type === 'income').reduce((sum, v) => sum + v.money, 0)
      const total = pay + income
      return { date: k, pay, income, total, list: v }
    })

  }, [monthGroup, curMonth])
  console.log('[ dailyBillList ] >', dailyBillList)
  // ]

  return (
    <div className="monthlyBill">
      <NavBar className="nav" backArrow={false}>
        月度收支
      </NavBar>
      <div className="content">
        <div className="header">
          {/* 时间切换区域 */}
          <div className="date" onClick={() => setDateVisible(true)}>
            <span className="text">
              {curMonth}月账单
            </span>
            <span className={classNames('arrow', { expand: dateVisible })}></span>
          </div>
          {/* 统计区域 */}
          <div className='twoLineOverview'>
            <div className="item">
              <span className="money">{overview.pay}</span>
              <span className="type">支出</span>
            </div>
            <div className="item">
              <span className="money">{overview.income}</span>
              <span className="type">收入</span>
            </div>
            <div className="item">
              <span className="money">{overview.total}</span>
              <span className="type">结余</span>
            </div>
          </div>
          {/* 时间选择器 */}
          <DatePicker
            className="kaDate"
            title="记账日期"
            precision="month"
            visible={dateVisible}
            max={new Date()}
            onConfirm={dateConfirm}
          />
        </div>

        {/* 日账单 */}
        {dailyBillList.map(v => (
          <DailyBill key={v.date} overview={v} />
        ))}
      </div>
    </div >
  )
}

export default Month